﻿/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/1/31 21:45:10
 *        Description: 暂无
 ***********************************************************************/


using System;
using ComprehensiveSystem.Configuration;
using ComprehensiveSystem.IRepository.UnitOfWork;
using ComprehensiveSystem.Loging;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using SqlSugar.IOC;
using NLog;

namespace ComprehensiveSystem.Repository.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly IConfiguration _configuration;

        private readonly IServiceProvider _serviceProvider;
        private ISqlSugarClient _dbClient;
        //private readonly ConcurrentDictionary<string, ISqlSugarClient> _dbClients = new();//将 ISqlSugarClient 实例存储在一个字典中，以实现按需创建并重用
        private bool _isTransactionActive;

        public UnitOfWork(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public ISqlSugarClient GetDbClient<T>() where T : class
        {
            var dbKey = DatabaseSelector.GetConnectionStringKey<T>();
 
            _dbClient = DbScoped.SugarScope.GetConnection(dbKey);

            return _dbClient;
        }

        public ISqlSugarClient GetDbClientByConfig<T>() where T : class
        {
            var dbKey = DatabaseSelector.GetConnectionStringKey<T>();
            var connectionString = _configuration.GetConnectionString(dbKey);
            return new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = connectionString,
                DbType = AppSettingsConstVars.DbDbType == "SqlServer" ? DbType.SqlServer : DbType.MySql, // 根据实际数据库类型设置 
                IsAutoCloseConnection = true
            });

            // 尝试从字典中获取 ISqlSugarClient 实例
            //return _dbClients.GetOrAdd(dbKey, key =>
            //{
            //    var connectionString = _configuration.GetConnectionString(key);
            //    return new SqlSugarClient(new ConnectionConfig
            //    {
            //        ConnectionString = connectionString,
            //        DbType = AppSettingsConstVars.DbDbType == "SqlServer" ? DbType.SqlServer : DbType.MySql, // 根据实际数据库类型设置  
            //        IsAutoCloseConnection = true
            //    });
            //});
        }

        public void BeginTran<T>() where T : class
        {
            if (!_isTransactionActive)
            {
                GetDbClient<T>().Ado.BeginTran();
                _isTransactionActive = true;
            }
            else
            {
                NLogUtil.WriteFileLog(LogLevel.Error, LogType.Web, "事务已经开始", "事务已经开始", new Exception("事务已经开始"));
            }
        }

        public void CommitTran<T>() where T : class
        {
            try
            {
                if (_isTransactionActive)
                {
                    GetDbClient<T>().Ado.CommitTran();
                    _isTransactionActive = false;
                }
            }
            catch (Exception ex)
            {
                _dbClient.Ado.RollbackTran();
                NLogUtil.WriteFileLog(LogLevel.Error, LogType.Web, "事务提交异常", "事务提交异常", new Exception("事务提交异常", ex));
                throw;
            }
        }

        public void RollbackTran<T>() where T : class
        {
            if (_isTransactionActive)
            {
                GetDbClient<T>().Ado.RollbackTran();
                _isTransactionActive = false;
            }
        }

    }
}